<?php

namespace App\Http\Middleware;

use App\Models\SysMenu;
use App\Models\SysUser;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SysPermission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $no_nedd_auth_url = ['api/v1/getInfo', 'api/v1/getRouters'];
        if(auth()->id() === 1 || in_array($request->path(), $no_nedd_auth_url)){
            return $next($request);
        }

        $request_route_name = $request->route()->getName();
        //获取授权用户菜单
        $perm = str_replace('.', ':', $request_route_name);

        $user = SysUser::with('roles')->where('id',auth()->id())->first();
        $roles = $user->roles;
        $roles_id = [];
        foreach ($roles as $role){
            $roles_id[] = $role->id;
        }
        //获取角色菜单
        $role_menus_id = DB::table('sys_role_menu')->whereIn('role_id',$roles_id)->pluck('menu_id');
        if($role_menus_id){
            $role_menus_id = array_unique($role_menus_id->toArray());
        }
        //获取菜单
        $perms_menus = SysMenu::whereIn('id',$role_menus_id)->where('menu_type', 'F')->pluck('perms');
        if(!in_array($perm, $perms_menus->toArray() )){
            return error('无权限');
        }
        return $next($request);
    }
}
